package com.hup.joystick.view.functionSetting.customView;

import com.hup.joystick.constant.DeviceKey.KeyActionType;
import com.hup.joystick.model.joystick.StandardEvent;
import com.hup.joystick.model.joystick.StandardEvent.StandardAction;
import com.hup.utils.commons.TextUtil;
import com.hup.utils.swing.ComponentUtil;
import com.hup.utils.swing.customView.KeyboardText.KeyChangedListener;
import com.hup.utils.swing.customView.NotInputTextView;
import lombok.Getter;
import lombok.Setter;

import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;

/**
 * 手柄按键Text
 * @author hugan
 * @date 2020/10/28
 */
public class JoyStandardKeyText extends NotInputTextView {

    @Getter
    private final ArrayList<String> lstStandardKey = new ArrayList<>();
    @Setter
    private KeyChangedListener keyChangedListener;

    @Override
    protected void processKeyEvent(KeyEvent e) {
        e.consume();
        if (e.getID() != KeyEvent.KEY_PRESSED) return;
        if (e.getKeyCode() == KeyEvent.VK_BACK_SPACE && !lstStandardKey.isEmpty()) {
            lstStandardKey.clear();
            updateTextByKey();
            if (keyChangedListener != null) keyChangedListener.onKeyChanged();
        }
    }

    private void updateTextByKey() {
        if (lstStandardKey.isEmpty()) {
            setText(null);
        } else {
            setText(TextUtil.getText(lstStandardKey, "+"));
        }
        ComponentUtil.afterChangedChild(this.getParent());
    }

    public void onJoyKeyEvent(StandardEvent e) {
        boolean isPressed = false;
        for (StandardAction action : e.actions) {
            if (action.actionType == KeyActionType.TYPE_PRESSED) {
                isPressed = true;
                break;
            }
        }
        if (!isPressed) return;//没有按下事件,忽略

        //有按下事件,则结果是当前所有按下的按钮
        lstStandardKey.clear();
        for (StandardAction press : e.currentPress) lstStandardKey.add(press.standardKey.key);
        updateTextByKey();
        if (keyChangedListener != null) keyChangedListener.onKeyChanged();
    }

    public void setStandardKey(List<String> standardKeys, boolean notifyListener) {
        lstStandardKey.clear();
        lstStandardKey.addAll(standardKeys);
        updateTextByKey();
        if (notifyListener && keyChangedListener != null) keyChangedListener.onKeyChanged();
    }

}
